﻿using AntdUI;
using DataCollection.Core.Models;
using DataCollection.Infrastructure;
using Microsoft.Office.Interop.Word;
using ScottPlot.Palettes;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DataCollection.WinForm.Forms
{
    public partial class ReportForm : DCBaseForm
    {
        #region 属性
        /// <summary>
        /// 试压项目
        /// </summary>
        public ProjectItem SelectedProjectItem = null!;

        /// <summary>
        /// 试压模板
        /// </summary>
        public TemplateModel SelectedTemplateModel = null!;

        /// <summary>
        /// 试压记录
        /// </summary>
        public HistoryModel SelectedHistoryModel = null!;

        /// <summary>
        /// 压力曲线图片地址
        /// </summary>
        public string PressureImagePath = string.Empty;

        /// <summary>
        /// 温度曲线图片地址
        /// </summary>
        public string TemperatureImagePath = string.Empty;

        /// <summary>
        /// 根地址
        /// </summary>
        private static readonly string ReportRootPath = Singleton.ReportRootPath;

        /// <summary>
        /// 模板路径
        /// </summary>
        private readonly string TemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template.docx");

        /// <summary>
        /// 报告缓存地址
        /// </summary>
        private string ReportTmpPath { get; set; } = null!;

        /// <summary>
        /// 报告地址
        /// </summary>
        private string ReportPath { get; set; } = null!;
        #endregion

        public void Export(string wordTemplatePath, string newFileName, Dictionary<string, string> wordLableList)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            string TemplateFile = wordTemplatePath;
            File.Copy(TemplateFile, newFileName);
            _Document doc = new Document();
            object obj_NewFileName = newFileName;
            object obj_Visible = false;
            object obj_ReadOnly = false;
            object obj_missing = System.Reflection.Missing.Value;
            doc = app.Documents.Open(ref obj_NewFileName, ref obj_missing, ref obj_ReadOnly, ref obj_missing,
                ref obj_missing, ref obj_missing, ref obj_missing, ref obj_missing,
                ref obj_missing, ref obj_missing, ref obj_missing, ref obj_Visible,
                ref obj_missing, ref obj_missing, ref obj_missing,
                ref obj_missing);
            doc.Activate();
            if (wordLableList.Count > 0)
            {
                object what = WdGoToItem.wdGoToBookmark;
                Bookmarks books = doc.Bookmarks;

                foreach (Bookmark bk in books)
                {
                    if (bk.Name == "ChartImage")
                    {
                        bk.Select();
                        Selection sel = app.Selection;
                        InlineShape img = sel.InlineShapes.AddPicture(wordLableList[bk.Name]);
                        img.ScaleHeight = float.Parse(Math.Floor(37 / AntdUI.Config.Dpi).ToString());
                    }
                    else if (bk.Name == "TemperatureImage")
                    {
                        bk.Select();
                        Selection sel = app.Selection;
                        InlineShape img = sel.InlineShapes.AddPicture(wordLableList[bk.Name]);
                        img.ScaleHeight = float.Parse(Math.Floor(37 / AntdUI.Config.Dpi).ToString());
                    }
                    else if (wordLableList.ContainsKey(bk.Name))
                    {
                        bk.Range.Text = wordLableList[bk.Name];
                    }
                }
            }
            object obj_IsSave = true;
            doc.SaveAs2(ReportPath, WdSaveFormat.wdFormatPDF);
            doc.Close(ref obj_IsSave, ref obj_missing, ref obj_missing);
            ExportResult();
        }

        private void ExportResult()
        {
            if (File.Exists(ReportPath))
            {
                string message = string.Format("【{0}】试压报告已导出", SelectedProjectItem.Name);
                AntdUI.Notification.success(this, "友情提示", message, autoClose: 10, align: TAlignFrom.TR);
            }
            else
            {
                ErrorNotification("试压报告导出失败");
            }
            Singleton.Instance.ReloadReportList();
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        private void DeleteTmpFile(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch (Exception)
                { 
                
                }
            }
        }

        private void ErrorNotification(string message)
        {
            AntdUI.Notification.error(this, "友情提示", message, autoClose: 0, align: TAlignFrom.TR);

        }

        #region 系统事件
        public ReportForm()
        {
            InitializeComponent();
            Header.Text = "试压报告";
            //FullScreen = true;
        }

        private void ReportForm_Load(object sender, EventArgs e)
        {
            if (File.Exists(PressureImagePath))
            {
                FileStream fileStream = new FileStream(PressureImagePath, FileMode.Open, FileAccess.Read);
                PressureImageBox.Image = Image.FromStream(fileStream);
                fileStream.Close();
                fileStream.Dispose();
            }
            if (SelectedProjectItem != null)
            {
                ProjectNameLabel.Text = SelectedProjectItem.Name;
                ProjectNumberLabel.Text = SelectedProjectItem.Number;
                StakeMarkLabel.Text = SelectedProjectItem.StakeMark;
                PipeSpecificationLabel.Text = SelectedProjectItem.PipeSpecification;
                DesignPressureLabel.Text = SelectedProjectItem.DesignPressure.ToString();
                PipeLengthLabel.Text = SelectedProjectItem.PipeLength;
                MediumLabel.Text = SelectedProjectItem.Medium;
                string startTime = DateTimeOffset.FromUnixTimeSeconds(SelectedHistoryModel.StartTime).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
                string endTime = DateTimeOffset.FromUnixTimeSeconds(SelectedHistoryModel.EndTime).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
                TimeLabel.Text = string.Format("{0} 至 {1}", startTime, endTime);
                ReportTmpPath = Path.Combine(ReportRootPath, string.Format("{0}.docx", SelectedProjectItem.Number));
                ReportPath = Path.Combine(Singleton.ExportPath, string.Format("{0}试压报告.pdf", SelectedProjectItem.Name));
            }

            if (SelectedTemplateModel != null)
            {
                IntensityPressureLabel.Text = SelectedTemplateModel.IntensityStagePressure.ToString();
                IntensityTimeLabel.Text = SelectedTemplateModel.IntensityStageTime.ToString() + SelectedTemplateModel.IntensityStageTimeUnit;
                IntensityDiffenceLabel.Text = "0";

                RigorPressureLabel.Text = SelectedTemplateModel.RigorStagePressure.ToString();
                RigorTimeLabel.Text = SelectedTemplateModel.RigorStageTime.ToString() + SelectedTemplateModel.RigorStageTimeUnit;
                RigorDiffenceLabel.Text = "0";
            }
            else
            {
                Error("试压模板信息不存在！");
            }

        }
        #endregion

        private void ExportButton_Click(object sender, EventArgs e)
        {
            if (SelectedProjectItem == null)
            {
                Error("项目信息不存在，无法导出报告");
                return;
            }
            string path;                              //文件路径变量
            Object missing = System.Reflection.Missing.Value; //定义空变量
            Object isReadOnly = false;
            path = TemplatePath;
            string newFileName = ReportTmpPath;
            Dictionary<string, string> wordLableList = new Dictionary<string, string>();
            wordLableList.Add("ProjectName", SelectedProjectItem.Name);
            wordLableList.Add("ProjectNumber", SelectedProjectItem.Number);
            wordLableList.Add("StakeMark", SelectedProjectItem.StakeMark);
            wordLableList.Add("PipeSpecification", SelectedProjectItem.PipeSpecification);
            wordLableList.Add("Pressure", SelectedProjectItem.DesignPressure.ToString());
            wordLableList.Add("PipeLength", SelectedProjectItem.PipeLength);
            wordLableList.Add("Medium", SelectedProjectItem.Medium);
            if (IntensityPressureLabel.Text != null)
            {
                wordLableList.Add("IntensityPressure", IntensityPressureLabel.Text);
            }

            if (IntensityTimeLabel.Text != null)
            {
                wordLableList.Add("IntensityTime", IntensityTimeLabel.Text);
            }

            if (IntensityDiffenceLabel.Text != null)
            {
                wordLableList.Add("IntensityDiffence", IntensityDiffenceLabel.Text);
            }
            if (RigorPressureLabel.Text != null)
            {
                wordLableList.Add("RigorPressure", RigorPressureLabel.Text);
            }

            if (RigorTimeLabel.Text != null)
            {
                wordLableList.Add("RigorTime", RigorTimeLabel.Text);
            }

            if (RigorDiffenceLabel.Text != null)
            {
                wordLableList.Add("RigorDiffence", RigorDiffenceLabel.Text);
            }

            string? time = TimeLabel.Text;
            if (time != null)
            {
                wordLableList.Add("Time", time);
            }

            if (File.Exists(PressureImagePath))
            {
                wordLableList.Add("ChartImage", PressureImagePath);
            }

            if (File.Exists(TemperatureImagePath))
            {
                wordLableList.Add("TemperatureImage", TemperatureImagePath);
            }

            if (File.Exists(TemplatePath))
            {
                DCSpin(this, "正在导出报告....", (config) =>
                {
                    Export(TemplatePath, ReportTmpPath, wordLableList);
                }, null, () =>
                {
                    DeleteTmpFile(ReportTmpPath);
                    DeleteTmpFile(TemperatureImagePath);
                    DeleteTmpFile(PressureImagePath);
                });
            }
            else
            {
                ErrorNotification("试压报告模板不存在");
            }
        }

        private void ReportForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
        }
    }
}
